package com.tusion.minio.controller;


import com.tusion.minio.utils.MinioUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@RestController
@RequestMapping({"/minio"})
public class MinioController {
    @Resource
    private MinioUtil minioUtil;

    @GetMapping({"/ok"})
    public String ok() {
        return "ok";
    }

    @PostMapping({"/fileUpload"})
    public String upload(@RequestPart("file") MultipartFile file) {
        if (Objects.isNull(file)) {
            return "请传入需要上传的文件";
        }
        return this.minioUtil.putObject(file);
    }

    @GetMapping({"/getFileUrl"})
    public String getFileUrl(@RequestParam("fileName") String fileName) {
        return this.minioUtil.getObjectUrl(fileName);
    }

    @ResponseBody
    @GetMapping({"/fileDownload"})
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        this.minioUtil.getObject(fileName, response);
    }

    @PostMapping({"/fileUpload/byBucket"})
    public String uploadByBucket(@RequestPart("file") MultipartFile file, @RequestParam("bucket") String bucket) {
        if (Objects.isNull(file)) {
            return "请传入需要上传的文件";
        }
        return this.minioUtil.putObjectByBucket(file, bucket);
    }

    @GetMapping({"/getFileUrl/byBucket"})
    public String getFileUrlByBucket(@RequestParam("fileName") String fileName, @RequestParam("bucket") String bucket) {
        return this.minioUtil.getObjectUrlByBucket(fileName, bucket);
    }

    @ResponseBody
    @GetMapping({"/fileDownload/byBucket"})
    public void downloadByBucket(@RequestParam("fileName") String fileName, @RequestParam("bucket") String bucket, HttpServletResponse response) {
        this.minioUtil.getObjectByBucket(fileName, bucket, response);
    }
}
